// 侧边栏的JavaScript，实现首页导航和基本功能

let apiService = null;

// 初始化函数
async function initializeApp() {
  try {
    // 动态导入API服务
    const module = await import(chrome.runtime.getURL('services/api-service.js'));
    apiService = module.default;
    await apiService.loadConfig();
  } catch (error) {
    console.error('API服务初始化失败:', error);
    showMessage('API服务初始化失败，请检查配置');
  }
}

document.addEventListener('DOMContentLoaded', async function() {
  // 获取DOM元素
  const tabButtons = document.querySelectorAll('.tab-btn, .settings-btn');
  const panels = document.querySelectorAll('.panel');
  const translateInput = document.getElementById('translate-input');
  const translateOutput = document.getElementById('translate-output');
  const summaryInput = document.getElementById('summary-input');
  const summaryOutput = document.getElementById('summary-output');
  const translateBtn = document.getElementById('translate-btn');
  const summarizeBtn = document.getElementById('summarize-btn');
  const copyTranslateBtn = document.getElementById('copy-translate-btn');
  const copySummaryBtn = document.getElementById('copy-summary-btn');
  const saveSettingsBtn = document.getElementById('save-settings');
  const cancelSettingsBtn = document.getElementById('cancel-settings');
  const resetSettingsBtn = document.getElementById('reset-settings');
  const apiUrlInput = document.getElementById('api-url');
  const apiKeyInput = document.getElementById('api-key');
  const targetLanguageSelect = document.getElementById('target-language');
  const summaryModelSelect = document.getElementById('summary-model');

  // 检查DOM元素是否都正确获取
  const elements = {
    translateInput,
    translateOutput,
    translateBtn,
    targetLanguageSelect,
    summaryInput,
    summaryOutput,
    summarizeBtn,
    summaryModelSelect,
    apiUrlInput,
    apiKeyInput
  };

  for (const [name, element] of Object.entries(elements)) {
    if (!element) {
      console.error(`未找到元素: ${name}`);
    }
  }

  // 初始化API服务和设置
  try {
    await initializeApp();
    await loadSettings();
  } catch (error) {
    console.error('初始化失败:', error);
    showMessage('初始化失败，请检查配置');
  }

  // 标签页切换功能
  tabButtons.forEach(button => {
    button.addEventListener('click', () => {
      const tabName = button.getAttribute('data-tab');
      console.log('切换到标签页:', tabName);
      
      // 更新活动标签按钮
      tabButtons.forEach(btn => {
        if (btn.classList.contains('tab-btn')) {
          btn.classList.remove('active');
        }
      });
      
      if (button.classList.contains('tab-btn')) {
        button.classList.add('active');
      }
      
      // 显示对应面板
      panels.forEach(panel => {
        panel.classList.remove('active');
        panel.style.display = 'none';
      });
      
      const targetPanel = document.getElementById(`${tabName}-panel`);
      if (targetPanel) {
        targetPanel.classList.add('active');
        targetPanel.style.display = 'flex';
      } else {
        console.error(`未找到面板: ${tabName}-panel`);
      }
    });
  });

  // 监听从后台脚本发送的消息
  chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    console.log('收到消息:', {
      action: request.action,
      textLength: request.text?.length
    });

    if (request.action === 'displaySelectedText') {
      try {
        // 获取当前活跃面板
        const activePanel = document.querySelector('.panel.active');
        console.log('当前活跃面板:', activePanel?.id);
        
        if (!activePanel) {
          throw new Error('未找到活跃面板');
        }

        // 根据面板类型选择输入框
        let textArea;
        if (activePanel.id === 'translate-panel') {
          textArea = document.getElementById('translate-input');
        } else if (activePanel.id === 'summary-panel') {
          textArea = document.getElementById('summary-input');
        }

        // 检查输入框是否存在
        if (!textArea) {
          throw new Error(`在${activePanel.id}中未找到输入框`);
        }

        console.log('正在更新输入框...', {
          panelId: activePanel.id,
          textAreaId: textArea.id
        });

        // 更新输入框内容
        textArea.value = request.text;
        console.log('输入框更新成功');
        
        // 发送成功响应
        sendResponse({ status: 'success' });
      } catch (error) {
        console.error('显示选中文本时出错:', error);
        showMessage(error.message);
        sendResponse({ status: 'error', message: error.message });
      }
    }
    return true;
  });

  // 复制按钮功能
  copyTranslateBtn?.addEventListener('click', () => {
    copyToClipboard(translateOutput.value);
    showMessage('已复制到剪贴板');
  });

  copySummaryBtn?.addEventListener('click', () => {
    copyToClipboard(summaryOutput.value);
    showMessage('已复制到剪贴板');
  });

  // 翻译按钮功能
  translateBtn?.addEventListener('click', async () => {
    if (!apiService) {
      showMessage('API服务未初始化，请刷新页面重试');
      return;
    }

    const text = translateInput.value.trim();
    if (!text) {
      showMessage('请输入需要翻译的文本');
      return;
    }

    const targetLang = targetLanguageSelect.value;
    translateBtn.disabled = true;
    translateBtn.textContent = '翻译中...';
    
    try {
      // 检查配置
      const config = await chrome.storage.sync.get(['apiUrl', 'apiKey']);
      console.log('当前配置状态:', {
        hasUrl: !!config.apiUrl,
        hasKey: !!config.apiKey,
        keyLength: config.apiKey ? config.apiKey.length : 0
      });

      if (!config.apiUrl || !config.apiKey) {
        throw new Error('请先在设置中配置API地址和API Key');
      }

      console.log('开始翻译:', {
        text,
        targetLang,
        apiUrl: config.apiUrl
      });

      const translatedText = await apiService.translateText(text, targetLang);
      
      if (!translatedText) {
        throw new Error('未获取到翻译结果');
      }

      console.log('翻译结果:', {
        originalLength: text.length,
        translatedLength: translatedText.length
      });

      translateOutput.value = translatedText;
    } catch (error) {
      console.error('翻译失败:', error);
      showMessage(error.message || '翻译失败，请稍后重试');
      translateOutput.value = '';
    } finally {
      translateBtn.disabled = false;
      translateBtn.textContent = '翻译';
    }
  });

  // 总结按钮功能
  summarizeBtn?.addEventListener('click', async () => {
    if (!apiService) {
      showMessage('API服务未初始化，请刷新页面重试');
      return;
    }

    const text = summaryInput.value.trim();
    if (!text) {
      showMessage('请输入需要总结的文本');
      return;
    }

    summarizeBtn.disabled = true;
    summarizeBtn.textContent = '总结中...';
    
    try {
      // 检查配置
      const config = await chrome.storage.sync.get(['apiUrl', 'apiKey']);
      console.log('当前配置状态:', {
        hasUrl: !!config.apiUrl,
        hasKey: !!config.apiKey,
        keyLength: config.apiKey ? config.apiKey.length : 0
      });

      if (!config.apiUrl || !config.apiKey) {
        throw new Error('请先在设置中配置API地址和API Key');
      }

      console.log('开始总结:', {
        textLength: text.length,
        model: summaryModelSelect.value
      });

      const summary = await apiService.summarizeText(text);
      
      if (!summary) {
        throw new Error('未获取到总结结果');
      }

      console.log('总结完成:', {
        originalLength: text.length,
        summaryLength: summary.length
      });

      summaryOutput.value = summary;
    } catch (error) {
      console.error('总结失败:', error);
      showMessage(error.message || '总结失败，请稍后重试');
      summaryOutput.value = '';
    } finally {
      summarizeBtn.disabled = false;
      summarizeBtn.textContent = '总结';
    }
  });

  // 设置页面功能
  saveSettingsBtn?.addEventListener('click', async () => {
    const apiUrl = apiUrlInput.value.trim();
    const apiKey = apiKeyInput.value.trim();
    
    if (!apiUrl) {
      showMessage('请输入API地址');
      return;
    }
    
    if (!apiKey) {
      showMessage('请输入API Key');
      return;
    }

    // 验证API地址格式
    try {
      new URL(apiUrl);
    } catch (e) {
      showMessage('API地址格式无效，请输入完整的URL（例如：https://api.example.com）');
      return;
    }
    
    try {
      console.log('准备保存设置:', {
        apiUrl,
        hasKey: !!apiKey,
        keyLength: apiKey.length
      });

      // 保存设置
      await chrome.storage.sync.set({
        apiUrl: apiUrl,
        apiKey: apiKey
      });
      
      // 立即验证设置是否保存成功
      const savedSettings = await chrome.storage.sync.get(['apiUrl', 'apiKey']);
      console.log('设置保存验证:', {
        apiUrl: savedSettings.apiUrl === apiUrl,
        hasKey: !!savedSettings.apiKey,
        keyLength: savedSettings.apiKey ? savedSettings.apiKey.length : 0,
        urlMatch: savedSettings.apiUrl === apiUrl
      });

      if (!savedSettings.apiUrl || !savedSettings.apiKey) {
        throw new Error('设置保存失败，请重试');
      }

      // 重新初始化API服务
      if (apiService) {
        console.log('正在重新初始化API服务...');
        await apiService.loadConfig();
        
        // 验证API服务配置
        const serviceConfig = {
          apiUrl: apiService.apiUrl,
          hasKey: !!apiService.apiKey,
          keyLength: apiService.apiKey ? apiService.apiKey.length : 0,
          isInitialized: apiService._initialized
        };
        console.log('API服务配置状态:', serviceConfig);

        if (!apiService.apiUrl || !apiService.apiKey) {
          throw new Error('API服务配置加载失败');
        }
      } else {
        console.error('API服务未初始化');
        throw new Error('API服务未初始化');
      }
      
      showMessage('设置已保存');
      // 切换回翻译页面
      document.querySelector('[data-tab="translate"]')?.click();
    } catch (error) {
      console.error('保存设置失败:', error);
      showMessage('保存设置失败: ' + error.message);
    }
  });

  cancelSettingsBtn?.addEventListener('click', () => {
    // 重新加载设置并返回翻译页面
    loadSettings();
    document.querySelector('[data-tab="translate"]')?.click();
  });

  resetSettingsBtn?.addEventListener('click', () => {
    // 重置为默认设置
    chrome.storage.sync.set({
      apiUrl: 'https://kimi-api.example.com',
      apiKey: ''
    }, () => {
      loadSettings();
      showMessage('设置已重置为默认值');
    });
  });

  // 加载设置
  async function loadSettings() {
    try {
      console.log('开始加载设置...');
      
      // 先检查storage权限
      const permissions = await chrome.permissions.getAll();
      console.log('当前权限:', permissions);

      const items = await chrome.storage.sync.get({
        apiUrl: 'https://kimi-api.example.com',
        apiKey: ''
      });
      
      console.log('从storage加载的设置:', {
        hasUrl: !!items.apiUrl,
        hasKey: !!items.apiKey,
        keyLength: items.apiKey ? items.apiKey.length : 0,
        apiUrl: items.apiUrl
      });
      
      // 验证URL格式
      try {
        if (items.apiUrl && items.apiUrl !== 'https://kimi-api.example.com') {
          new URL(items.apiUrl);
        }
      } catch (e) {
        console.error('已保存的API地址格式无效:', items.apiUrl);
        items.apiUrl = 'https://kimi-api.example.com';
      }
      
      apiUrlInput.value = items.apiUrl;
      apiKeyInput.value = items.apiKey;
      
      if (apiService) {
        console.log('正在初始化API服务配置...');
        await apiService.loadConfig();
        
        // 验证API服务配置
        console.log('API服务配置状态:', {
          apiUrl: apiService.apiUrl,
          hasKey: !!apiService.apiKey,
          keyLength: apiService.apiKey ? apiService.apiKey.length : 0,
          isInitialized: apiService._initialized
        });
      } else {
        console.warn('API服务未初始化，跳过配置加载');
      }
    } catch (error) {
      console.error('加载设置失败:', error);
      showMessage('加载设置失败: ' + error.message);
      throw error;
    }
  }

  // 复制到剪贴板
  function copyToClipboard(text) {
    if (!text) return;
    
    navigator.clipboard.writeText(text).catch(err => {
      console.error('无法复制文本: ', err);
    });
  }

  // 显示消息
  function showMessage(msg) {
    // 创建消息元素
    const messageDiv = document.createElement('div');
    messageDiv.className = 'message';
    messageDiv.textContent = msg;
    document.body.appendChild(messageDiv);

    // 2秒后自动消失
    setTimeout(() => {
      messageDiv.remove();
    }, 2000);
  }
}); 